<template>
  <!-- ============================================用户管理====================================== -->
  <el-container>
    <el-header style="height: 40px;padding-right: 10px;">
      <div style="display: flex;align-items: center;height: 40px;">
        <div style="flex-grow:1;font-size: 16px;font-weight: bold;">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item v-for="(item, index) in breadcrumb" :key="index">{{ item }}</el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div style="display:flex;align-items: center;">
          <div style="margin-right:15px;">
            <el-input @input="keyWordSerach()" v-model="searchData.keyWord" size="small" placeholder="关键字搜索" />
          </div>
					<slot></slot>
          <el-button-group style="margin-right:15px;">
            <el-button size="small" type="primary" icon="Search" @click="btnSearch()">查询</el-button>
            <el-button size="small" type="primary" icon="ArrowDownBold" @click="isshowdrawer = true"></el-button>
          </el-button-group>
          <el-button size="small" type="info" icon="Refresh" plain @click="reset()">重置</el-button>
          <el-button size="small" type="success" icon="CirclePlus" @click="addData()">新建</el-button>
          <!-- <el-button size="small" type="success" icon="CirclePlus" @click="openCanvasDialogFn()">绘制板</el-button> -->
        </div>
      </div>
    </el-header>
    <el-main>
      <el-table class="diytablebox"
      ref="tableRef" 
      height="100%"
      :data="tableData"
      :row-style="(e) => $store.state.tableRowStyle(e, rowStyle)"
      :header-cell-style="$store.state.outheaderstyle"
      @row-click="rowClick"
      @filter-change="filterChange" 
      @selection-change="handleSelectionChange" 
      @cell-dblclick="cellDBClick"
      @sort-change="sortChange"
      @row-contextmenu="rowContextMenu"
      row-key="id"
      size="small">
				<el-table-column v-if="!props.config.table_config.hideSelection" type="selection" fixed="left"></el-table-column>
				<el-table-column v-if="props.config.table_config.hideSerial" type="index" fixed="left" label="序号" width="50"></el-table-column>
				<el-table-column v-for="(item, index) in props.config.table_config.column" :key="index"
					v-bind="getColumnAttribute(item)">
					<template #default="scope" v-if="item.slot">
						<slot :name="item.prop" :row="scope.row" :_index="scope.$index"></slot>
					</template>
				</el-table-column>
					
        <el-table-column align="center" :width="props.config.table_config.opeWidth?props.config.table_config.opeWidth:'200px'" fixed="right" label="操作">
          <template #default="scope">
            <div style="display: flex;justify-content: flex-end;">
              <slot name="table_btn" :row="scope.row" :_index="scope.$index"></slot>
              <el-button v-if="!props.config.table_config.noEdit" size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
              <el-button v-if="!props.config.table_config.noDelete" size="small" type="danger" @click="handleDelete(scope.row, 1)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-main>
    <el-footer>
      <div style="display: flex;align-items: center;height: 45px;">
        <div style="flex-grow: 1">
          <el-button v-if="!props.config.table_config.noDeleteMore" size="small" style="" type="danger" icon="Delete" @click.stop="deletechoose">批量删除</el-button>
        </div>
        <el-pagination
          size="small"
          v-model:currentPage="searchData.page"
          v-model:page-size="searchData.limit"
          :page-sizes="searchData.pageSizes"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="searchData.totalItemCount"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-footer>
    <!-- =================================== 弹出层 ================================ -->
    <el-dialog custom-class="diyDialog" class="diyDialog" 
    v-model="openDialog" :before-close="(done) => beforeClose(done)" 
    destroy-on-close
    :title="'列表详情'" width="1050px">
    
      <div class="contentbox_border border" :style="'max-height: ' + (store.state.dialog_body_height) + 'px;overflow-y: auto;'">
        <!-- <data-detail v-if="dialogSwitch == 'data_detail'" ref="data_detail" @close-dialog="closeDialog"></data-detail> -->
				<slot name="dialog_slot" :data="sendData"></slot>
			</div>
      
      <template #footer>
        <div class="dialog-footer">
          <slot name="dialog_btn"></slot>
          <el-button @click="clickClose()">关闭</el-button>
        </div>
      </template>

    </el-dialog>
    <!-- =========================================================================== -->

    <el-drawer
      v-model="isshowdrawer"
      title="高级筛选"
      direction="rtl"
    >
      <!-- :before-close="drawerHandleClose" -->
      <slot name="search_slot" :adv_search="searchData">
        <div class="flexbox" style="margin-bottom:10px;">
          <div class="searchContent">企业名称：</div>
          <div class="searchBox" style="width:100%;">
            <el-input placeholder="请输入企业名称" v-model="searchData.enterpriseName"></el-input>
          </div>
        </div>
      </slot>

      <template #footer>
        <div style="flex: auto">
          <el-button size="small" @click="isshowdrawer=false">关闭</el-button>
          <el-button size="small" type="info" icon="Refresh" @click="reset()">重置</el-button>
          <el-button size="small" type="primary" @click="btnSearch()">查询</el-button>
        </div>
      </template>
    </el-drawer>

    <!-- ====================================右键菜单================================== -->
    <context-menu-pop>
      <template #pop_body>
        <div style="cursor: pointer;padding:3px 0;font-size: 14px;">
          <slot name="contextMenu_slot" :row="contextMenuData">
            <div class="clickitem" @click="contextMenuClick()">
              <div class="itemleft">功能1</div>
              <div class="itemright"></div>
            </div>
            <div class="clickitem" @click="contextMenuClick()">
              <div class="itemleft">功能2</div>
              <div class="itemright"></div>
            </div>
            <div class="clickitem" @click="contextMenuClick()">
              <div class="itemleft">功能3</div>
              <div class="itemright"></div>
            </div>
          </slot>
        </div>
        
      </template>
    </context-menu-pop>


  </el-container>
</template>

<script setup>
  import ContextMenuPop from '@/components/Jm_ContextMenu/jm_popMenu.vue'

  // import useMixin from '@/assets/utils/useMixin'

  // console.log(useMixin())
  // const { mData } = useMixin()

  // console.log(mData)
  import { reactive, ref, onMounted, inject, nextTick, defineProps, defineEmits, defineExpose } from 'vue'
  import { useStore } from 'vuex'
  // 注入全局utils工具js
  const $utils = inject('$utils')
  // 注入全局filters工具js
  const $filters = inject('$filters')
  // 定义store
  const store = useStore()
  // 设置行的颜色，空值为默认值
  const rowStyle = reactive({ id: '', color: '' })
	// 定义$emit事件
	const emit = defineEmits()





  // 
  const dialogSwitch = ref('')

  // 定义子组件的ref
  const data_detail = ref()

  // 定义定时器
  const timmer = ref(null)

	
  // ======================================================================== 入参声明
	const props = defineProps({
		config: {
				type: Object,
				default: {
          // 标题
          breadcrumb: [],
          // 是否开启右键事件
          openContextMenu: false,
					// 基础信息配置
					operation: {
						// 获取表单列表数据URL——GetPageList
						get_data_url: '',
						// 获取表单列表详情数据URL——GetEdit
						get_detaildata_url: '',
						// 删除表单列表数据URL——DoBatchDelete
						del_data_url: '',
						// 配置弹出哪个弹窗内容
						checkref: 'data_detail'
					},
					table_config: {
            // 是否隐藏序号
            hideSerial: false,
            // 设置操作行宽度
            opeWidth: '',
						// 是否隐藏多选行
						hideSelection: false,
						// 是否不开启单行删除
            noDelete: false,
						// 是否不开启编辑功能
            noEdit: false,
						// 是否不开启批量删除
            noDeleteMore: false,
						// 表格信息配置
						column: []
					}
				}
		}
	})
	const operationData = props.config.operation

	// 传输到父组件的值
	const sendData = ref({})


  // *********************************定义变量**********************************
  // 页眉
  const breadcrumb = ref(['测试小标题'])
  // 是否开启详细查询
  const isshowdrawer = ref(false)
  // // 筛选条件分布
  // const filterData = ref({
  //   userName: [
  //     { text: '测试1', value: '测试1' }, 
  //     { text: '测试2', value: '测试2' }
  //   ]
  // })
  // 定义table的ref绑定
  const tableRef = ref()
  // 筛选条件
  const searchData = ref({
    page: 1,
    pageSizes: [30, 100, 200, 300, 400],
    limit: 30,
    totalItemCount: 100,
    keyWord: ''
  })
  // 批量选择的数据
  const chooseTableData = ref()
  // 初始化表格数据
  const tableData = ref([])
  // 是否开启弹窗
  const openDialog = ref(false)
  // 右键获取的值
  const contextMenuData = ref({})
  // ******************************************************* 进入页面时方法 *************************************************************

  // 进入该模块执行的方法
  const onMountedHook = function () {
    console.log('进入该modal模块执行的方法')
    breadcrumb.value = props.config.breadcrumb?props.config.breadcrumb:['测试小标题']
    if (store.state.isOldRouter || store.state.routerMode_refrash) {
      getData()
    }
  }

	// ################# 动态配置Column表格属性值
	function getColumnAttribute(obj) {
		return obj
		// const resObj = {}
		// for (let key in obj) {
		// 	resObj[key] = obj[key]
		// }
		// return resObj
	}

  // ********************************************************************************************************************
  // ------------------ 右键菜单事件 ---------------------------
  function rowContextMenu(row, column, event) {
    contextMenuData.value = row
    rowStyle.id = row.id
    if (!props.config.openContextMenu) return
    event.preventDefault()
    store.commit('set_pop_attr', {
      pop_show: true, 
      get_event: event
    })
    // console.log(event)
    // console.log(row)
    // console.log(column)
   
  }
  // ----------------- 默认右键点击选择菜单事件 -------------------------
  function contextMenuClick() {
    store.commit('set_pop_attr', {
      pop_show: false
    })
  }
  // **************************************************************************

  // **************************************************************************

  // // 保存数据提交方法
  // function saveData() {
	// 	emit('checkData', {
	// 		checkref: operationData.checkref,
	// 		fn: 'submitData'
	// 	})
  // }
  // 输入关键字查询
  function keyWordSerach() {
    if (timmer.value) {
      clearTimeout(timmer.value)
    }
    timmer.value = setTimeout(() => {
      btnSearch()
    }, 300)
  }
  // 查询第一页数据方法
  function btnSearch() {
    searchData.value.page = 1
    getData()
  }
  // 获取数据方法
  function getData() {
    tableData.value = []
		if (!operationData.get_data_url) {
			for (let i = 0; i < 40; i++) {
			  tableData.value.push({
			    userName: '测试' + i,
					nickName: '昵称' + i,
			    id: i
			  })
			}
			return
		}
    $utils.post({
      url: operationData.get_data_url,
      params: searchData.value,
      ok: function (res) {
        tableData.value = res.data
        searchData.value.totalItemCount = res.count
      }
    })
  }
  // 新建列表方法
  function addData() {
    showView()
		emit('checkData', {
			checkref: operationData.checkref,
			fn: 'initData',
			data: {}
		})

  }
  // 编辑数据方法
  async function handleEdit(index, item) {
    // 查询详情数据
    const res = await getPageData(item)
    if (res.data.code == 0) {
      showView()
			emit('checkData', {
				checkref: operationData.checkref,
				fn: 'initData',
				data: res.data.data
			})

    }

  }
  // 删除数据方法
  function handleDelete(item, flag) {
    // 删除方法相应的字段
    const del_Id = 'id'
    const ids = []
    if (flag == 0) {
      item.forEach(item => {
        ids.push(item[del_Id])
      })
    } else {
      ids.push(item[del_Id])
    }
		if (!operationData.del_data_url) return
    $utils.post({
      url: operationData.del_data_url,
      params: { id: ids },
      confirm: true,
      showLoading: true,
      ok: function (res) {
        getData()
      }
    })
  }
  // 批量删除数据方法
  function deletechoose() {
    if (chooseTableData.value.length == 0) {
      $utils.message({
        showClose: true,
        center: true,
        message: '请选择操作数据',
        type: 'warning'
      })
    } else {
      handleDelete(chooseTableData.value, 0)
    }
  }
  function getPageData(item) {
		if (!operationData.get_detaildata_url) return { data: { code: 0, data: { orderCode: '123' } } }
    return $utils.post({
      url: operationData.get_detaildata_url,
      params: {
        id: item.id
      },
      showLoading: true,
      noasync: true
    })
  }
  // ====================== 关闭弹窗事件 ===========================
  // 筛选展示的弹窗组件
  function showView() {
    openDialog.value = true
    // dialogSwitch.value = type
  }
  function beforeClose(done, flag) {
    if (flag || store.state.close_showtip) {
      $utils.showCloseTip(function () {
        done()
        getData()
      })
    } else {
      done()
      getData()
    }
  }
  function closeDialog() {
    openDialog.value = false
    getData()
  }
  function clickClose() {
    openDialog.value = false
  }
  // *******************************修改分页*******************************
  // 改变每页条数方法
  function handleSizeChange(val) {
    searchData.value.limit = val
    getData()
  }
  // 改变页数方法
  function handleCurrentChange(val) {
    searchData.value.page = val
    getData()
  }
  // **************************************************************

  // *******************************Table操作*******************************
  // 多选数据
  function handleSelectionChange(val) {
    chooseTableData.value = val
  }
  // 行单击事件
  function rowClick(row, column, e) {
    rowStyle.id = row.id
  }
  // 标题头筛选
  function filterChange(filters) {
    const key = Object.keys(filters)[0]
    searchData.value[key] = filters[key]
    getData()
  }
  // 行双击事件
  function cellDBClick(row, column, cell, event) {
    handleEdit(1, row)
  }
  // 排序筛选
  function sortChange(obj) {
    if (!obj.prop) {
      searchData.value.orderBy = ''
    } else {
      searchData.value.orderBy = obj.prop + ' ' + obj.order
    }
    getData()
  }
  
  // 重置查询条件方法
  function reset() {
    tableRef.value.clearFilter()
    searchData.value = $utils.resetForm(searchData.value)
    btnSearch()
  }
  // **************************************************************

  onMounted(() => {
    onMountedHook()
  })
  // 外部自定义 弹窗及按钮 事件
  function diyBtnFn(obj) {
    showView()
    emit('checkData', obj)
  }

  // 高级筛选条件传入并搜索
  function advSearch(fn) {
    if (!!fn) {
      fn()
    }
    btnSearch()
  }

	defineExpose({
    // 关闭窗口并查询新数据
		closeDialog,
    // 仅关闭窗口
    clickClose,
    // 外部自定义 弹窗及按钮 事件
    diyBtnFn,
    // 高级筛选条件传入并搜索
    advSearch
	})

</script>

<style scoped>
.el-container {
  height: 100%;
}
.el-header {
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-bottom:none;
  border-radius: 5px 5px 0 0;
}
.el-main {
  padding: 0;
  background-color:#fff;
  border:1px solid #DDE2E8;
}
.el-footer {
  height:45px;
  border-radius: 0 0 5px 5px;
  background-color:#fff;
  border:1px solid #DDE2E8;
  border-top:none;
}
/* .diyDialog :deep(.el-dialog__body) {
  padding: 0 !important;
}  */
/deep/ .el-dialog__body {
  padding: 0 15px 0 15px !important;
}
/deep/ .el-dialog {
  margin: 30px auto 30px !important;
  overflow: hidden !important;
}
</style>